Implementint sqrt(int x).

Compute and return the square root ofx, where x is guaranteed to be a non-negative integer.

Since the return type is an integer, the decimal digits are truncated and only the integer part of the result is returned.

Example 1:

Input:
 4

Output:
 2

Example 2:

Input:
 8

Output:
 2

Explanation:
 The square root of 8 is 2.82842..., and since 
             the decimal part is truncated, 2 is returned.

class Solution {

public:

int mySqrt\(int x\) {

    int result=0;

    if \(\(x>=1\) && \(x<=3\)\)return 1;

    if \(x==INT\_MAX\) return 46340;



    for\(int i=0;i<=x/2;i++\){

        if \(i\*i>x\){

            result= i-1;

            break;

        }

        else{

            result=i;

            if \(i\*i==x\) break;

        }



    }

    return result;

}

};

要注意的是,一个是要截尾,还有一个是INT_MAX的处理

results matching ""

    No results matching ""